<html><head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <script src="jquery.js"></script>
  <script src="jquery.flot.js"></script>
  <script src="jquery.flot.valuelabels.js"></script>
  <link href="plot.css" rel="stylesheet" type="text/css"/>
  <link href="popup.css" rel="stylesheet" type="text/css"/>

  <script src="prefs.js"></script>
  <script src="tools.js"></script>
  <script src="fetchers.js"></script>
<script type="text/javascript">

var port = null;
var tabport = null;
var uri = null;
var request_url = null;
var whitelisted = false;
var counter = 0;

var timelines = {  // a map of fetcher id to [ fetcher, timeline ]
};

function uris_to_top(uri) { //FIXME: move to TOOLS
  var ret = [];
  // we expect schema://hostname.or.ip/partx/party/partz#safdo?akuhfd
  var tail = uri.search(/[#?&]/)
  if (-1==tail) {
    ret.push(uri);
  } else {
    ret.push(uri.substr(0, tail));
    ret.push(uri);
    uri = uri.substr(0, tail);
  }
  tail = uri.lastIndexOf('/');
  if (tail+1==uri.length) {
    uri = uri.substr(0, tail);
    tail = uri.lastIndexOf('/', tail);
  }
  while (tail>10) {
    ret.push(uri.substr(0, tail+1));
    tail = uri.lastIndexOf('/', tail-1);
  }
  return ret;
}

function init() {
  SeoprofesionalTools.translate();
  var request_params = SeoprofesionalTools.getRequestParams(window.location.href, "popup.html");
  request_url = request_params.url;
  if (!request_url || request_params.showmenu) {
    document.getElementById("head").style.display = "block";
    document.getElementById("menu").style.display = "block";
    document.getElementById("status").style.display = "block";
  }
  if (request_url) {
    request_url = unescape(request_url);
  }
  if ("chartlinks" in request_params) {
    switchView = switchView2;
  }

  port = chrome.extension.connect({name: "seoppopup"});
  port.onMessage.addListener(function(msg) {
    if ("status"==msg.type) {
      if ("disabled"==msg.info) {
        document.getElementById("status").className = "disabled";
      } else if ("unavailable"==msg.info) {
        document.getElementById("status").className = "unavailable";
      } else {
        document.getElementById("status").className = "enabled";
      }
    } else if ("url"==msg.type) {
      uri = msg.url;
      if (msg.data) {
        var s = "";
        for (var ff = 0; ff<SeoprofesionalFetchers.length;ff++) {
          var f = SeoprofesionalFetchers[ff];
          if (f.enabled && f.id in msg.data) {
            s+= f.nicename + ": <b>" + msg.data[f.id] + "</b><br>";
          }
        }
        if (!s) {
          s = chrome.i18n.getMessage("noranks");
        }
        document.getElementById("values").innerHTML = s;
        switchView("values");
      }
      // construct links
      var menulinks = prefsGetJSON("menulinks", SeoprofesionalTools.default_menulinks);
      var links = document.getElementById("links");
      s = "<div id='menulinks_head'>" + chrome.i18n.getMessage("menulinks_head") + "</div>"
      for (var i = 0;i<menulinks.length;i++) {
        if (menulinks[i][0]) {
          var name = menulinks[i][1];
          var templ = menulinks[i][2];

          if (-1!=templ.indexOf("%s")) {
            templ = templ.replace("%s", escape(uri));
          } else if (-1!=templ.indexOf("%d")) {
            templ = templ.replace("%d", escape(SeoprofesionalTools.get_domain(uri)));
          }
          s+= "<div class='menulink' onclick='chrome.tabs.create({url:" + '"' + templ + '"' + "})'>" + name + "</div>";
        }
      }
      links.innerHTML = s;
    } else if ("whitelist"==msg.type) {
      whitelisted = msg.value;
      if (null==msg.value) {
        var to_top = uris_to_top(uri);
        var s = chrome.i18n.getMessage("click_to_whitelist") + "<ul>";
        for (var i = 0; i<to_top.length; i++) {
          s+= '<li onclick="whitelist(\'' + to_top[i] +'\')">' + to_top[i] + '</li>';
        }
        s+= "</ul>";
        document.getElementById("whitelist").innerHTML = s;
        document.getElementById("whitelist_btn").src = "wd.png";
      } else {
        var s = chrome.i18n.getMessage("click_to_unwhitelist") + "<br>" + whitelisted + "?<div>";
        s+= '<input type="button" onclick="unwhitelist()" value="' + chrome.i18n.getMessage("yes") + '"/>';
        s+= '<input type="button" onclick="switchView(\'chart\')" value="' + chrome.i18n.getMessage("no") + '"/></div>';
        document.getElementById("whitelist").innerHTML = s;
        document.getElementById("whitelist_btn").src = "we.png";
      }
    } else if ("dataset"==msg.type) {
      timelines[msg.fetcher.id] = [ msg.fetcher, msg.value ];
      do_plot(null);
    }
  });
  reset_view();
}
function toggle() {
  port.postMessage({type:"toggle"});
  reset_view();
}
function whitelist(u) {
  port.postMessage({type:"whitelist", url: u});
    reset_view();
}

var datasets = [];  // datasets for flot.plot
var ranks = [];  // the order of the ranks in datasets
var origdata = [];

function do_plot(uri) {
  var date_format = chrome.i18n.getMessage("dateformat");

  origdata.splice(0, origdata.length+1);
  datasets.splice(0, datasets.length+1);
  ranks.splice(0, ranks.length+1);

  switchView("chart");

  for (var ff = 0; ff<SeoprofesionalFetchers.length;ff++) {
    var f = SeoprofesionalFetchers[ff];
    if (f.enabled && f.id in timelines) {
      var tl = timelines[f.id][1];
      if (tl.length>0) {
        var data = [];
        var od = [];
        var last = null;
        for (var i = 0;i<tl.length;i++) {
          var tm = new Date();
          tm.setTime(tl[i][0]);
          tm.setSeconds(0);
          tm.setMinutes(0);
          tm.setHours(10);
          tm.setMilliseconds(0);

          if (f.coherent) {
          } else if (null!=last && last[1]!=tl[i][1]) {
            data.push(null);
            od.push(null);
          }
          data.push([ tm, tl[i][1]/f.get_max(tl)*100 ]);
          od.push([tm, tl[i][1]]);
          last = tl[i];
        }
        if (data.length) {
            datasets.push({
              data: data,
              label: f.nicename,
              color: f.color,
              valueLabelFunc: formatValue
            });
            origdata.push(od);
            ranks.push(f);
        }
      }
    }
  }

  $.plot($("#chart"), datasets, {
    xaxis: { mode: "time", timeformat: date_format, labelHeight: 50, labelWidth:2 },
    yaxis: { min:0, max: 105, tickFormatter: function(axis,v) {return '';} },
    //y2axis: { min:0, max: 10 },
    points: { show: true, radius: 2 },
    lines: { show: true, fill: false },
    grid: { hoverable: true },
    valueLabels: { show: true, valueLabelFunc: formatValue },
    legend: { position: 'nw' }
  });
  function formatValue(item) {
    return origdata[item.seriesIndex][item.index][1];
  }

  var previousPoint = null;
  $("#chart").bind("plothover", function (event, pos, item) {
    if (item) {
      if (previousPoint != item.datapoint) {
        previousPoint = item.datapoint;

        $("#tooltip").remove();
        var d = origdata[item.seriesIndex][item.dataIndex];
        var contents = SeoprofesionalTools.format_date(d[0], date_format) + ":<br>" + ranks[item.seriesIndex].nicename + "=" + d[1];
        $('<div id="tooltip">' + contents + '</div>').css( {
          top: item.pageY + 5,
          left: item.pageX + 5,
        }).appendTo("body").fadeIn(200);
      }
    } else {
      $("#tooltip").remove();
      previousPoint = null;
    }
  });
}
function unwhitelist() {
    if (whitelisted) {
        port.postMessage({type:"unwhitelist", url:whitelisted});
        reset_view();
    }
}
function reset_view() {
    if (request_url) {
        port.postMessage({type:"get", url:request_url});
    } else {
        port.postMessage({type:"current"});
    }
}
/*
 * Switch the tab in our UI.
 */
function switchView(tab) {
    var tabs = [ "whitelist", "chart", "values", "links", "hl" ];
    for (var i = 0; i<tabs.length; i++) {
        document.getElementById(tabs[i]).style.display = (tab==tabs[i] ? "block" : "none");
    }
}
function switchView2(tab) {
  document.getElementById("padding").style.display = "none";
  document.getElementById("whitelist").style.display = "none";
  document.getElementById("values").style.display = "none";
  document.getElementById("hl").style.display = "none";
  document.getElementById("chart").style.display = "block";
  document.getElementById("links").style.display = "block";
}
function hlupdated() {
  document.getElementById("hlinfo").innerHTML = "";
  if (tabport) {
    tabport.postMessage({"action":"select", "type": document.getElementById("hltype").value});
  }
}
function hl_link(frme, idx) {
  if (tabport) {
    tabport.postMessage({"action":"focus", "frame": frme, "index":idx});
  }
}
function add_hl_item(el, m) {
    el.addEventListener("mouseover", function() { hl_link(m.frame, m.index); }, false);
}
function onhl() {
  switchView("hl");
  if (null==tabport) {
    chrome.tabs.getSelected(null, function(tab) {
      tabport = chrome.tabs.connect(tab.id, { name:"seophl"});
      tabport.onMessage.addListener(function(msg) {
        for (var i = 0;i<msg.length;i++) {
          var m = msg[i];
          var el = document.createElement("li");
          el.innerText = m.href + " " + m.index;
          add_hl_item(el, m);
          document.getElementById("hlinfo").appendChild(el);
        }
      });
      hlupdated();
    });
  } else {
    hlupdated();
  }
}
</script>
</head><body onload="init()">
<div id="head" onclick="chrome.tabs.create({url: chrome.i18n.getMessage('about_url')})"></div>
<div id="status" onclick="toggle()"></div>
<div id="menu">
<img id="whitelist_btn" src="wd.png" onclick='switchView("whitelist")'/>
<img src="links.png" onclick='switchView("links")'/>
<img src="hl.png" onclick='onhl()'/>
<br><br><br><br>
<img src="ranks.png" onclick='chrome.tabs.create({url: "utility.html"})'/>
<img src="general.png" onclick='chrome.tabs.create({url: "options.html"})'/>
</div>
<div id="padding"></div>
<div id="content">
    <div id="chart"></div>
    <div id="whitelist"></div>
    <div id="values"></div>
    <div id="links"></div>
    <div id="hl">
      <span class="trans">highlight</span> <select id="hltype" onchange="hlupdated()">
        <option class="trans" value="none">nothing</option>
        <option class="trans" value="all">all_links</option>
        <option class="trans" value="nofollow">nofollow_links</option>
        <option class="trans" value="internal">internal_links</option>
        <option class="trans" value="external">external_links</option>
      </select>
      <ol id="hlinfo"></ol>
    </div>
</div>
</body></html>

